<?php
namespace app\www\controller;
use x\my\pay\Alipay;
use x\my\Pay;
class Order extends Base{

    //创建订单
    public function createOrder(){
        $d = $this->post();
        $rule = [
            'goods_price_ids' => 'require',
            'address_id' => 'require',
            'pay_money' => 'require',
            'pay_type' => 'require',
            'goods_type' => 'require',
        ];
        $msg = [
            'goods_price_ids.require' => '未选中商品',
            'address_id.require' => '未选择收货地址',
            'pay_money.require' => '支付金额必填',
            'pay_type.require' => '支付方式必填',
            'goods_type.require' => '商品类型必填',
        ];
        check($rule, $msg, $d);
        $goods = $d['goods_price_ids'];
        err('微信支付未开通');

        $order_nos = s("orderGoods", "c")->add($this->userinfo['id'], $d['address_id'], $goods,$d['goods_type'],'');
        if(!$order_nos) err(s("orderGoods", "c")->getError());

        //在线支付
        if($d['pay_money']){
            //充值余额
            $recharge_order_no = m('recharge', 'c')->add($this->userinfo['id'], $d['pay_money'], $d['pay_type'],'在线购买','order_goods',0,implode(',',$order_nos));
            if(!$recharge_order_no) err(m("recharge", "c")->getError());
            #充值信息
            $recharge_info = $this->db->query("select * from recharge where order_no=?",[$recharge_order_no],1);
            $total_fee = bcmul($recharge_info['money'],100);

            #微信 #4 统一下单
            if($d['pay_type']==0){
                $rs = [];
              #七色淘品
              $config = [
                'app_id' => c('api.wx_gzh_appid'),
                'mch_id' => c('api.wx_pay_mchid'),
                'key'    => c('api.wx_pay_key'),
                'mode'   => 'optional',
              ];
              $pay = Pay::wechat($config);
              $order = [
                'body' => '在线购买',
                'out_trade_no' => $recharge_info['order_no'],
                'total_fee' => $total_fee,
                'notify_url' => url('notice/wxrecharge'),
            ];

              // 扫码支付使用 模式二
              $result = $pay->scan($order);
              $txt = $result->code_url;
              $data = [
                  'qr_code'=>url('com/qrcode',['txt'=>$txt]),
              ];
              suc($data);
            #支付宝
            }else if($d['pay_type']==1){
                err('支付宝支付,暂未开放');
            }
        //直接付
        }else{
            foreach ($order_nos as $value) {
                $pay_rs = s("orderGoods", "c")->pay($value);
            }
            suc();
        }
    }

    //循环查询用户余额充值订单是否完成
    public function forEachUserRecharge(){
        $d = $this->post();
        if(!isset($d["order_no"])){
            err("订单不存在!");
        }
        $order_no = $d["order_no"];
        //查询商品订单
        $map = [];
        $map[] = ["and","order_no","=",$order_no];
        $map[] = ["and","pay_status","=",1];
        $w = where($map);
        $recharge_info = $this->db->query("select * from recharge $w[0]",$w[1],1);
        if(!$recharge_info){
            err("订单未支付!");
        }
        $this->payOk($d['order_goods_no']);
    }

    /**
     * [payOk 订单支付成功]
     * @param  string $order_no [订单编号]
     * @return [type]           [json]
     */
    private function payOk($order_no=''){
        if(!$order_no){
            cookie('js_url',url('/user/myCart'));
            err("参数错误!");
        }
        //查询商品订单
        $map = [];
        $map[] = ["and","order_no","=",$order_no];
        $w = where($map);
        $order_goods_list = $this->db->query("select * from order_goods $w[0]",$w[1]);
        if(empty($order_goods_list)){
            cookie('js_url',url('/user/myCart'));
            err("订单不存在!");
        }
        $order_total_price = $order_goods_list[0]['order_total_money'];
        if($this->userinfo["money"] < $order_total_price){
            cookie('js_url',url('/user/myCart'));
            err("用户余额不足!".$this->userinfo["money"]);
        }
        $this->db->begin();
        $mysql = [];
        //修改订单支付状态
        $d = ["pay_status"=>1];
        $map = ['order_no=?', [$order_no]];
        $mysql[] = $this->db->update("order_goods",$d,$map);
        foreach ($order_goods_list as $k => $v) {
            m('goods','c')->updateStock($v['nums'],$v['goods_price_id']);
        }

        #插入账单
        $mysql[] = m('Userbill', 'xcom')->doit($order_no, $this->userinfo['id'], 200, 'order_goods',  $order_goods_list[0]['id'],  $order_total_price, 'money','消费',0);
        $rs = $this->db->end($mysql);
        if(!$rs){
            log_test('wxpay_result_db',$mysql);
            err('支付账单失败');
        }
        //添加金额日志
        cookie('js_url',url('/user/orderlist'));
        cookie('js_msg',"支付成功");
        suc();
    }

    //订单详情
    public function detail(){
        $d = $this->get();
        $order_no = "";
        if(isset($d['out_trade_no'])){ //同步支付回调
            $model = m("Recharge","c");
            $order_goods_info = $model->getRechargeTableInfo($d['out_trade_no']);
            $order_no = $order_goods_info['order_no'];
        }else{
            $order_no = $d["order_no"];
        }
        if(!$order_no){
            cookie('js_url',url('/user/orderList'));
            err("订单不存在!");
        }
        $sql = "select * from order_goods where order_no = ? order by id desc";
        $rs = $this->db->query($sql,[$order_no]);
        $rule = [
            'pay_status' => function($v){return c("type.pay_status.{$v}");},
            'fahuo_status' => function($v){return c("type.fahuo_status.{$v}");},
            'create_time' => 'com_time_format',
        ];
        $data = com_format($rs,$rule);
        $this->fetch(['info'=>$data],'',false);
    }

    /**
     * 申请退款
     * [refundmoney description]
     * @return [type] [description]
     */
    public function refundmoney(){
        $d = $this->post();
        if(!isset($d['id'])){
            err("参数错误!");
        }
        $info = $this->db->query('select * from order_goods where id=? and user_id=?',[$d['id'],$this->userinfo['id']],1);
        if(!$info){
            err("订单不存在!");
        }
        $m = m('orderGoods','c');
        $rs = $m->apply_refund($d['id']);
        if($rs){
            cookie('js_function','preload');
            cookie('js_msg',"申请成功");
            suc();
        }else{
            err($m->getError());
        }
    }
}
?>
